<template>
  <el-space class="panel-container" direction="vertical" :fill-ratio="100" :size="0" fill wrap>
    <el-tabs v-model="activeTab2" type="card" :style="{ height: pagePanelHeight + 'px' }">
      <el-tab-pane :label="i18nt('designer.hint.page')" name="3">
        <div class="page-toolbar">
          <el-tooltip content="新建页面" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-document-add" @click="addPage"></el-button>
          </el-tooltip>
          <el-tooltip content="删除页面" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-document-remove" @click="deletePage"></el-button>
          </el-tooltip>
          <el-tooltip content="插入页面" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-expand" @click="insertPage"></el-button>
          </el-tooltip>
          <el-tooltip content="上移页面/组件" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-top" @click="moveUpPage"></el-button>
          </el-tooltip>
          <el-tooltip content="下移页面/组件" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-bottom" @click="moveDownPage"></el-button>
          </el-tooltip>
          <el-tooltip content="复制页面" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-copy-document" @click="copyPage"></el-button>
          </el-tooltip>

          <!-- 新增导出页面按钮 -->
          <el-tooltip content="导出页面" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-document" @click="exportPage"></el-button>
          </el-tooltip>
          <!-- 新增导入页面按钮 -->
          <el-tooltip content="导入页面" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-download" @click="importPage"></el-button>
          </el-tooltip>

          <!-- <el-tooltip content="清除页面" placement="top" effect="light">
            <el-button link type="primary" icon="el-icon-delete" @click="deleteAllPage"></el-button>
          </el-tooltip> -->
        </div>
        <el-scrollbar class="setting-scrollbar" :style="{ height: pageScrollBarHeight + 'px' }" always>
          <el-tree ref="treeRef" :data="nodeTreeData" :props="{ label: 'label' }" class="node-tree" node-key="id"
            highlight-current accordion :expand-on-click-node="false" icon-class="el-icon-arrow-right"
            @node-click="onNodeTreeClick"></el-tree>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>

    <div class="resize-line resize-line-vertical" @mousedown="resizeMousedownHandler"></div>

    <el-tabs v-model="activeTab" type="card" :style="{ height: settingsPanelHeight + 'px' }">
      <el-tab-pane :label="i18nt('designer.hint.widgetSetting')" name="1">
        <el-scrollbar class="setting-scrollbar" :style="{ height: settingsScrollBarHeight + 'px' }" always>
          <template v-if="selectedWidget">
            <el-form :model="optionModel" size="small" label-position="right" label-width="90px" class="setting-form"
              @submit.prevent>
              <el-collapse v-model="collapseNames" class="setting-collapse">
                <el-collapse-item v-if="appearancePropList.length > 0" name="1" title="外观">
                  <template v-for="editorName in appearancePropList" :key="editorName">
                    <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                      :option-model="optionModel"></component>
                  </template>
                </el-collapse-item>

                <el-collapse-item v-if="positionSizePropList.length > 0" name="2" title="位置尺寸">
                  <template v-for="editorName in positionSizePropList" :key="editorName">
                    <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                      :option-model="optionModel" :parent-widget="designer"></component>
                  </template>
                </el-collapse-item>

                <el-collapse-item v-if="miscPropList.length > 0" name="3" title="杂项">
                  <template v-for="editorName in miscPropList" :key="editorName">
                    <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                      :option-model="optionModel"></component>
                  </template>
                </el-collapse-item>

                <el-collapse-item v-if="fontPropList.length > 0" name="4" title="字体">
                  <template v-for="editorName in fontPropList" :key="editorName">
                    <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                      :option-model="optionModel"></component>
                  </template>
                </el-collapse-item>

                <el-collapse-item v-if="dataPropList.length > 0" name="3" title="数据">
                  <template v-for="editorName in dataPropList" :key="editorName">
                    <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                      :option-model="optionModel"></component>
                  </template>
                </el-collapse-item>

                <el-collapse-item v-if="eventPropList.length > 0" name="6" title="事件">
                  <template v-for="editorName in eventPropList" :key="editorName">
                    <component :is="editorName" :designer="designer" :selected-widget="selectedWidget"
                      :option-model="optionModel"></component>
                  </template>
                </el-collapse-item>
              </el-collapse>
            </el-form>
          </template>
        </el-scrollbar>
      </el-tab-pane>

      <el-tab-pane :label="i18nt('designer.hint.pageSetting')" name="2">
        <el-scrollbar class="setting-scrollbar" :style="{ height: settingsScrollBarHeight + 'px' }" always>
          <page-setting :pages="workspace.pages" :designer="designer" :page-options="pageOptions"></page-setting>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>

    <!-- <el-dialog v-model="showWidgetEventDialogFlag"
      :title="`${i18nt(`designer.widgetLabel.${selectedWidget && selectedWidget.type}`)}组件${curEventName}编辑`" :modal="false"
      :show-close="true" class="code-editor-dialog small-padding-dialog" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" :destroy-on-close="true" draggable>
  <div class="variable-info" v-if="selectedWidget">
    <p>控件ID : {{selectedWidget.options.name}}</p>
    <p >当前函数的通用变量(以下变量只在当前控件的范围有效)</p>
<p>objId : 指的是当前控件的ID（{{ selectedWidget.options.name }}），可以通过函数get_obj_width、get_obj_height、set_obj_width、set_obj_attr_ext1等函数获取和设置控件信息</p>
      <p>value : 当前控件的值</p>
  </div>
      <code-editor ref="ecEditor" v-model="eventHandlerCode" :mode="'lua'" :readonly="false"></code-editor>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showWidgetEventDialogFlag = false">
            {{ i18nt('designer.hint.cancel') }}</el-button>
             <el-button type="success" @click="handleWidgetPreview">
          {{ i18nt('designer.hint.simulate') }}</el-button>
          <el-button type="primary" @click="saveEventHandler">
            {{ i18nt('designer.hint.confirm') }}</el-button>
        </div>
      </template>
    </el-dialog> -->
  </el-space>
</template>

<script>
import * as ELECTRON from '@/electron'
import PageSetting from './page-setting.vue'
import { traverseAllWidgets } from '@/utils/util'
import emitter from '@/mixins/emitter'
import { deepClone } from '@/utils/util'
import { generateId } from '@/utils/util'
import { createDesigner } from '../designer'

import {
  APPEARANCE_PROPERTIES,
  POSITION_SIZE_PROPERTIES,
  FONT_PROPERTIES,
  DATA_PROPERTIES,
  MISC_PROPERTIES,
  EVENT_PROPERTIES
} from '@/designer/setting-panel/propertyRegister'
import * as EVENTS from '@/designer/event'
import { DESIGNER_TYPE } from '@/designer/const'

export default {
  name: 'SettingPanel',
  componentName: 'SettingPanel',
  components: {
    PageSetting
  },
  mixins: [emitter],
  props: {
    designer: Object,
    workspace: Object,
    mainHeight: {
      type: Number,
      default: window.innerHeight - 64
    }
  },
  data() {
    return {
      activeTab: '1',
      activeTab2: '3',
      collapseNames: ['1', '2', '3', '4', '5', '6'],

      showWidgetEventDialogFlag: false,
      eventHandlerCode: '',
      curEventName: '',

      subFormChildWidgetFlag: false,

      // resize
      pagePanelHeight: 300,
      isResizing: false,
      tabList: [],
    }
  },
  computed: {
    widgetValue() {
      if (!this.selectedWidget) return null;
      const options = this.selectedWidget.options;
      switch (this.selectedWidget.type) {
        case 'number':
        if (options.type === 'modbus') 
          return ` ${options.widgetValue || 0}`;
        if (options.type === 'userData') 
          return ` ${options.widgetValue || 0}`;
        return options.widgetValue || 0;
        case 'text':
          return options.widgetValue;
        case 'progress':
        case 'slider':
          return options.pos;
        case 'qrCode':
        case 'staticText':
          return options.strLabel;
        case 'switch':
          return options.selectLeftText || options.selectRightText;
        default:
          return null;
      }
    },
    hasWidgetValue() {
      return this.widgetValue !== null;
    },
    settingsPanelHeight() {
      return this.mainHeight - this.pagePanelHeight - 10
    },
    pageScrollBarHeight() {
      return this.pagePanelHeight - 50
    },
    settingsScrollBarHeight() {
      return this.settingsPanelHeight - 25
    },
    optionModel() {
      return this.selectedWidget.options
    },
    selectedWidget() {
      if (!this.designer) {
        return null
      }
      return this.designer.selectedWidget
    },
    pageOptions() {
      if (!this.designer) {
        return {}
      }
      return this.designer.options || {}
    },
    widgetList() {
    if (!this.designer) {
      return []
    }
    return (this.designer.widgetList || []).filter(item => item != null) // 过滤 null
  },
    nodeTreeData() {
      // console.log(this.workspace)
      const pages = this.workspace.pages || []
      return pages.map((page) => {
        let children = []
        page.widgetList.map((widget) => {
          if (widget) {
            this.buildTreeNodeOfWidget(widget, children)
          }
        })
        return {
          id: page.id,
          label: page.options.name,
          type: page.type,
          children
        }
      })
    },
    appearancePropList() {
      // console.log('3=====> ')
      // console.log(APPEARANCE_PROPERTIES)
      // console.log(this.optionModel)
      if (!this.optionModel) {
        return []
      }
      return Object.keys(APPEARANCE_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return APPEARANCE_PROPERTIES[prop]
        })
    },
    positionSizePropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(POSITION_SIZE_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return POSITION_SIZE_PROPERTIES[prop]
        })
    },
    fontPropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(FONT_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return FONT_PROPERTIES[prop]
        })
    },
    dataPropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(DATA_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return DATA_PROPERTIES[prop]
        })
    },
    miscPropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(MISC_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return MISC_PROPERTIES[prop]
        })
    },
    eventPropList() {
      if (!this.optionModel) {
        return []
      }
      return Object.keys(EVENT_PROPERTIES)
        .filter((prop) => {
          return Object.hasOwn(this.optionModel, prop)
        })
        .map((prop) => {
          return EVENT_PROPERTIES[prop]
        })
    }
  },
  watch: {
    'selectedWidget.options': {
      //组件属性变动后，立即保存表单JSON！！
      deep: true,
      handler() {
        if (this.designer) {
          this.designer.saveCurrentHistoryStep()
        }
      }
    },

    pageOptions: {
      deep: true,
      handler() {
        if (this.designer) {
          this.designer.saveCurrentHistoryStep()
        }
      }
    },
    designer: {
      deep: true,
      handler(value) {
        if (value) {
          if (value.selectedWidget && value.selectedWidget.id) {
            this.activeTab = '1'
          } else {
            this.activeTab = '2'
          }
        }
      }
    }
  },
  created() {
    // console.log('created...')
    this.on$('editEventHandler', (eventParams) => {
      //debugger
      this.editEventHandler(eventParams[0], eventParams[1])
    })
  },
  mounted() {
    document.addEventListener('mousemove', this.resizeMousemoveHandler)
    document.addEventListener('mouseup', this.resizeMouseupHandler)
  },
  unmounted() {
    document.removeEventListener('mousemove', this.resizeMousemoveHandler)
    document.removeEventListener('mouseup', this.resizeMouseupHandler)
  },
  methods: {
    showEditModal(widget) {
      if (widget.type === 'button') {
        this.editButtonWidget = widget
        this.showButtonEditModal = true
        return
      }

      if (widget.type === 'slidePage') {
        this.editSlideWidget = widget
        this.showSlideEditModal = true
        return
      }

      this.editModuleWidget = widget
      this.showModuleEditModal = true
    },
    saveAllUnsavedCodeTabs(callback) {
  // 确保 this.tabList 存在
  if (!this.tabList) {
    console.error('tabList is not defined');
    callback?.();
    return;
  }
  
  // 强制同步更新所有待保存标签页
  this.tabList.forEach(tab => {
    if (tab.hasUnsavedChanges && 
        (tab.type === 'page-code' || tab.type === 'widget-code' || tab.type === 'sub-lua-code')) {
      // 立即更新到内存
      if (tab.type === 'page-code') {
        const page = this.workspace.pages.find(p => p.id === tab.pageId);
        if (page) page.options.code = tab.content;
      } else if (tab.type === 'widget-code') {
        const widget = this.findWidgetInPages(tab.widgetId);
        if (widget) widget.options[tab.eventName] = tab.content;
      } else if (tab.type === 'sub-lua-code') {
        const subLua = this.workspace.subLuaList.find(item => item.name === tab.subLuaName);
        if (subLua) {
          subLua.code = tab.content;
        } else {
          this.workspace.subLuaList.push({
            name: tab.subLuaName,
            code: tab.content
          });
        }
      }
      tab.hasUnsavedChanges = false; // 立即清除标记
    }
  });

  // 强制同步保存到文件
  this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK); 

  // 执行回调（仿真操作）
  callback?.();
},
    saveToJson() {
    this.saveAllUnsavedCodeTabs()
    this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK)
  },
    createPageDesigner(name, page) {
  const size = {
    width: this.workspace.settings.width,
    height: this.workspace.settings.height
  }
  
  const designer = createDesigner(this, size, name, page);  // 这里正确传递了 this (vue 实例)
  
  // 使用箭头函数确保this指向正确
  designer.saveToJson = () => {
    this.saveAllUnsavedCodeTabs();
    this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK);
  };
  
  return designer;
},


// 新方法：递归设置所有组件为可编辑状态
setWidgetsEditable(widgetList) {
  if (!widgetList) return
  
  widgetList.forEach(widget => {
    if (!widget) return
    
    widget.readOnly = false
    if (widget.options) {
      widget.options.readOnly = false
    }
    widget.selectable = true
    widget.draggable = true
    widget.resizable = true
    
    // 递归处理子组件
    if (widget.widgetList) {
      this.setWidgetsEditable(widget.widgetList)
    }
  })
},
    // 在methods中添加以下方法
exportPage() {
  console.log('执行exportPage方法');
  
  if (!this.designer) {
    console.error('designer未定义:', this.designer);
    this.$message.warning('请先选择要导出的页面');
    return;
  }

  try {
    console.log('准备导出页面:', this.designer.options.name);
    
    // 准备导出的页面数据 - 保持所有组件名称不变
    const pageData = {
      id: this.designer.id,
      type: this.designer.type,
      options: deepClone(this.designer.options),
      // 直接克隆widgetList，不修改任何组件名称
      widgetList: deepClone(this.designer.widgetList)
    };

    console.log('导出数据:', pageData);

    // 创建Blob对象
    const blob = new Blob([JSON.stringify(pageData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    // 创建下载链接
    const a = document.createElement('a');
    a.href = url;
    a.download = `${this.designer.options.name || 'page'}.json`;
    document.body.appendChild(a);
    a.click();
    
    // 清理
    setTimeout(() => {
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      console.log('导出完成，已清理资源');
    }, 100);

  } catch (error) {
    console.error('导出失败:', error);
    this.$message.error(`导出失败: ${error.message}`);
  }
},

async importPage() {
  if (!this.designer) {
    this.$message.warning('请先选择要导入的位置')
    return
  }

  try {
    // 创建文件输入元素
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.json'
    
    // 处理文件选择
    const file = await new Promise((resolve, reject) => {
      input.onchange = (e) => {
        if (e.target.files.length > 0) {
          resolve(e.target.files[0])
        } else {
          reject(new Error('未选择文件'))
        }
      }
      input.click()
    })
    
    // 读取文件内容
    const content = await new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => resolve(e.target.result)
      reader.onerror = (e) => reject(new Error('文件读取失败'))
      reader.readAsText(file)
    })
    
    // 解析JSON
    let importedPage
    try {
      importedPage = JSON.parse(content)
      // 确保导入的页面数据是可编辑的
      importedPage.readOnly = false
      importedPage.options = importedPage.options || {}
      importedPage.options.readOnly = false
      
      // 递归设置所有组件为可编辑状态
      const setWidgetsEditable = (widgetList) => {
        if (!widgetList) return
        
        widgetList.forEach(widget => {
          if (!widget) return
          
          widget.readOnly = false
          widget.options = widget.options || {}
          widget.options.readOnly = false
          widget.selectable = true
          widget.draggable = true
          widget.resizable = true
          
          // 确保组件有必要的属性
          if (!widget.id) {
            widget.id = generateId()
          }
          if (widget.options && !widget.options.name) {
            widget.options.name = `${widget.type}_${generateId()}`
          }
          
          // 递归处理子组件
          if (widget.widgetList) {
            setWidgetsEditable(widget.widgetList)
          }
        })
      }
      
      setWidgetsEditable(importedPage.widgetList)
    } catch (e) {
      throw new Error('JSON解析失败，请检查文件格式')
    }
    
    // 验证导入的数据结构
    if (!importedPage || !importedPage.type || !importedPage.widgetList) {
      throw new Error('无效的页面数据格式')
    }
    
    // 确认导入
    await this.$confirm(`确定要导入页面 "${importedPage.options?.name || '未命名'}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 处理导入的页面数据
    const newPage = {
    ...importedPage,
    id: DESIGNER_TYPE.UI + generateId() + '',
    options: {
      ...importedPage.options,
      name: this.getUniquePageName(importedPage.options?.name || 'imported_page'),
      readOnly: false
    },
    widgetList: this.regenerateWidgetIds(deepClone(importedPage.widgetList))
  }
  
  // 创建页面设计器实例并绑定方法
  const pageDesigner = this.createPageDesigner(newPage.options.name, newPage)
  pageDesigner.saveToJson = this.saveToJson.bind(this)
    
    // 插入到当前页面之后
    const currentIndex = this.workspace.pages.findIndex(p => p.id === this.designer.id)
    if (currentIndex !== -1) {
      this.workspace.pages.splice(currentIndex + 1, 0, pageDesigner)
    } else {
      this.workspace.pages.push(pageDesigner)
    }
    
    // 强制更新视图
    this.$forceUpdate()
    
    // 使用事件触发页面切换
    this.$emitter.emit(EVENTS.ACTIVATE_PAGE_TAB, pageDesigner)
    
    // 立即保存项目
    this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
      callback: () => {
        this.$message.success('页面导入成功')
      }
    })
     this.$nextTick(() => {
    if (this.designer) {
      this.designer.setSelected(null) // 先取消选中
      this.$forceUpdate() // 强制重新渲染
    }
  })
    
  } catch (error) {
    if (error !== 'cancel') {
      this.$message.error(`导入失败: ${error.message || error}`)
    }
  }
},
// 新方法：重新生成所有组件的ID，但保持名称不变
regenerateWidgetIds(widgetList) {
  if (!widgetList) return []
  
  return widgetList.map(widget => {
    if (!widget) return null
    
    const newWidget = {
      ...widget,
      id: generateId(), // 生成新ID
      options: {
        ...widget.options
        // 保持名称不变
      },
      // 确保可编辑属性
      readOnly: false,
      selectable: true,
      draggable: true,
      resizable: true
    }
    
    // 递归处理子组件
    if (newWidget.widgetList && newWidget.widgetList.length > 0) {
      newWidget.widgetList = this.regenerateWidgetIds(newWidget.widgetList)
    }
    
    return newWidget
  }).filter(Boolean)
},

// 辅助方法：生成唯一的页面名称
getUniquePageName(baseName) {
  let name = baseName
  let counter = 1
  const existingNames = this.workspace.pages.map(p => p.options.name)
  
  while (existingNames.includes(name)) {
    name = `${baseName}_${counter}`
    counter++
  }
  
  return name
},

// 辅助方法：处理导入的组件数据
processImportedWidgets(widgetList) {
  if (!widgetList) return []
  
  return widgetList.map(widget => {
    if (!widget) return null
    
    const newWidget = {
      ...widget,
      id: generateId(),
      options: {
        ...widget.options,
        name: this.getUniqueWidgetName(widget.options?.name || widget.type),
        readOnly: false // 确保组件是可编辑的
      },
      // 添加以下属性确保可编辑
      selectable: true,
      draggable: true,
      resizable: true,
      contextMenu: widget.contextMenu || true
    }
    
    if (newWidget.widgetList && newWidget.widgetList.length > 0) {
      newWidget.widgetList = this.processImportedWidgets(newWidget.widgetList)
    }
    
    return newWidget
  }).filter(Boolean)
},

// 辅助方法：生成唯一的组件名称
getUniqueWidgetName(baseName) {
  let name = baseName
  let counter = 1
  const allWidgets = []
  
  // 收集所有现有组件的名称
  this.workspace.pages.forEach(page => {
    traverseAllWidgets(page.widgetList, widget => {
      if (widget && widget.options && widget.options.name) {
        allWidgets.push(widget.options.name)
      }
    })
  })
  
  while (allWidgets.includes(name)) {
    name = `${baseName}_${counter}`
    counter++
  }
  
  return name
},
    resizeMousedownHandler() {
      this.isResizing = true
    },
    resizeMouseupHandler() {
      this.isResizing = false
    },
    resizeMousemoveHandler(e) {
      if (this.isResizing) {
        const pagePanelHeight = Math.floor(this.pagePanelHeight + e.movementY)
        if (pagePanelHeight < 100) {
          this.pagePanelHeight = 100
        } else if (pagePanelHeight > this.mainHeight - 100) {
          this.pagePanelHeight = this.mainHeight - 100
        } else {
          this.pagePanelHeight = pagePanelHeight
        }
      }
    },
    editEventHandler(eventName) {
      this.curEventName = eventName
      this.eventHandlerCode = this.selectedWidget.options[eventName] || ''
      
      // 触发打开代码标签页
      this.$emitter.emit('open-widget-code-tab', {
        id: this.selectedWidget.id,
        name: `${this.selectedWidget.options.name}-${eventName}`,
        content: this.eventHandlerCode,
        type: 'widget-code',
        widgetId: this.selectedWidget.id,
        eventName: eventName
      })
    },
    handleWidgetPreview() {
      // 先保存代码但不关闭对话框
      this.saveEventHandler(false).then((success) => {
        if (success) {
          // 触发页面仿真
          this.$emitter.emit(ELECTRON.CLEAR_DEBUG_LOG)
          this.$emitter.emit(
            ELECTRON.START_PAGE_DEBUG,
            (this.designer && this.designer.options.name) || ''
          )
        }
      })
    },

    saveEventHandler(closeDialog = true) {
      return new Promise((resolve) => {
        const codeHints = this.$refs.ecEditor.getEditorAnnotations()
        let syntaxErrorFlag = false
        if (!!codeHints && codeHints.length > 0) {
          codeHints.forEach((chItem) => {
            if (chItem.type === 'error') {
              syntaxErrorFlag = true
            }
          })

          if (syntaxErrorFlag) {
            this.$message.error(this.i18nt('designer.setting.syntaxCheckWarning'))
            resolve(false)
            return
          }
        }

        this.selectedWidget.options[this.curEventName] = this.eventHandlerCode
        if (closeDialog) {
          this.showWidgetEventDialogFlag = false
        }
        resolve(true)
      })
    },
    setCurrentKey(id) {
      this.$refs.treeRef.setCurrentKey(id)
    },
    onNodeTreeClick(nodeData) {
  if (nodeData.selectable !== undefined && !nodeData.selectable) {
    this.$message.info(this.i18nt('designer.hint.currentNodeCannotBeSelected'))
    return
  }

  const selectedId = nodeData.id
  // 如果选中的是PAGE
  if (nodeData.type === DESIGNER_TYPE.UI) {
    const selectedPage = this.workspace.pages.find((page) => page.id === selectedId)
    this.$emitter.emit(EVENTS.ACTIVATE_PAGE_TAB, selectedPage)
    this.activeTab = '2'
    return
  }

  // 如果选中的是组件（包括嵌套组件）
  const pages = this.workspace.pages || []
  for (const page of pages) {
    const foundW = this.findWidgetById(selectedId, page.widgetList)
    if (foundW) {
      const selectedPage = this.workspace.pages.find((p) => p.id === page.id)
      this.$emitter.emit(EVENTS.ACTIVATE_PAGE_TAB, selectedPage)
      this.$nextTick(() => {
        this.designer.setSelected(foundW)
        this.activeTab = '1'
        // 确保树节点高亮
        this.setCurrentKey(foundW.id)
      })
      break
    }
  }
},
    buildTreeNodeOfWidget(widget, treeNode = []) {
  let curNode = {
    id: widget.id,
    label: widget.options.name || widget.type,
    type: widget.type  // 确保type属性被设置
  }
  treeNode.push(curNode)
  curNode.children = []
  if (widget.widgetList && widget.widgetList.length > 0) {
    // 递归处理子组件
    widget.widgetList.forEach((wChild) => {
      this.buildTreeNodeOfWidget(wChild, curNode.children)
    })
  }
},
    findWidgetById(selecteId, widgetList) {
  let foundW = null
  const traverse = (widgets) => {
    for (const widget of widgets) {
      if (!widget) continue // 跳过 null
      if (widget.id === selecteId) {
        foundW = widget
        return true
      }
      if (widget.widgetList?.length > 0) {
        if (traverse(widget.widgetList)) {
          return true
        }
      }
    }
    return false
  }
  traverse(widgetList)
  return foundW
},

    addPage() {
      this.$confirm(`确定要新建页面吗？`)
        .then(() => {
          this.$emitter.emit(EVENTS.NEW_PAGE)
        })
        .catch(() => { })
    },
    deletePage() {
      if (!this.designer) {
        this.$message.warning('请先选择删除的页面')
        return
      }

      this.$confirm(`确定要删除 ${this.designer.options.name} 页面吗？`)
        .then(() => {
          this.$emitter.emit(EVENTS.DELETE_PAGE, this.designer)
        })
        .catch(() => { })
    },
    insertPage() {
      if (!this.designer) {
        this.$message.warning('请先选择插入页面的位置')
        return
      }
      this.$confirm(`确定要插入页面吗？`)
        .then(() => {
          this.$emitter.emit(EVENTS.INSERT_PAGE, this.designer)
        })
        .catch(() => { })
    },

    // 移动向上
// moveUpPage() {
//   if (!this.designer) {
//     this.$message.warning('请先选择要移动的页面')
//     return
//   }

//   if (this.activeTab === '2') {
//     this.$emitter.emit(EVENTS.MOVE_UP_PAGE, this.designer)
//   } else {
//     const selectedWidget = this.designer.selectedWidget
//     if (!selectedWidget) return

//     const filteredList = this.widgetList.filter(item => item != null) // 先过滤 null
//     const index = filteredList.findIndex(item => item.id === selectedWidget.id)
    
//     if (index <= 0) return

//     // 交换位置
//     const temp = filteredList[index - 1]
//     filteredList[index - 1] = filteredList[index]
//     filteredList[index] = temp

//     // 更新原 widgetList（确保不引入 null）
//     this.designer.widgetList = [...filteredList]
    
//     this.$nextTick(() => {
//       this.setCurrentKey(selectedWidget.id)
//     })
//     this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK)
//   }
// },

// moveDownPage() {
//   if (!this.designer) {
//     this.$message.warning('请先选择要移动的页面')
//     return
//   }

//   if (this.activeTab === '2') {
//     this.$emitter.emit(EVENTS.MOVE_DOWN_PAGE, this.designer)
//   } else {
//     const selectedWidget = this.designer.selectedWidget
//     if (!selectedWidget) return

//     const filteredList = this.widgetList.filter(item => item != null) // 先过滤 null
//     const index = filteredList.findIndex(item => item.id === selectedWidget.id)
    
//     if (index === -1 || index + 1 >= filteredList.length) return

//     // 交换位置
//     const temp = filteredList[index + 1]
//     filteredList[index + 1] = filteredList[index]
//     filteredList[index] = temp

//     // 更新原 widgetList（确保不引入 null）
//     this.designer.widgetList = [...filteredList]
    
//     this.$nextTick(() => {
//       this.setCurrentKey(selectedWidget.id)
//     })
//     this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK)
//   }
// },

// 修改后的 moveUpPage 方法
moveUpPage() {
  if (!this.designer) {
    this.$message.warning('请先选择要移动的页面')
    return
  }

  if (this.activeTab === '2') {
    this.$emitter.emit(EVENTS.MOVE_UP_PAGE, this.designer)
  } else {
    const selectedWidget = this.designer.selectedWidget
    if (!selectedWidget) return

    // 查找组件所在的父级容器
    let parentContainer = null
    let widgetList = []
    
    // 先检查是否是页面级组件
    const pageWidgetIndex = this.widgetList.findIndex(item => item && item.id === selectedWidget.id)
    if (pageWidgetIndex !== -1) {
      widgetList = this.widgetList
    } else {
      // 如果不是页面级组件，则查找嵌套的父组件
      parentContainer = this.findParentContainer(this.widgetList, selectedWidget.id)
      if (parentContainer) {
        widgetList = parentContainer.widgetList || []
      } else {
        return
      }
    }

    const filteredList = widgetList.filter(item => item != null)
    const index = filteredList.findIndex(item => item.id === selectedWidget.id)
    
    if (index <= 0) return

    // 交换位置
    const temp = filteredList[index - 1]
    filteredList[index - 1] = filteredList[index]
    filteredList[index] = temp

    // 更新原 widgetList
    if (parentContainer) {
      parentContainer.widgetList = [...filteredList]
    } else {
      this.designer.widgetList = [...filteredList]
    }
    
    this.$nextTick(() => {
      this.setCurrentKey(selectedWidget.id)
    })
    this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK)
  }
},

// 修改后的 moveDownPage 方法
moveDownPage() {
  if (!this.designer) {
    this.$message.warning('请先选择要移动的页面')
    return
  }

  if (this.activeTab === '2') {
    this.$emitter.emit(EVENTS.MOVE_DOWN_PAGE, this.designer)
  } else {
    const selectedWidget = this.designer.selectedWidget
    if (!selectedWidget) return

    // 查找组件所在的父级容器
    let parentContainer = null
    let widgetList = []
    
    // 先检查是否是页面级组件
    const pageWidgetIndex = this.widgetList.findIndex(item => item && item.id === selectedWidget.id)
    if (pageWidgetIndex !== -1) {
      widgetList = this.widgetList
    } else {
      // 如果不是页面级组件，则查找嵌套的父组件
      parentContainer = this.findParentContainer(this.widgetList, selectedWidget.id)
      if (parentContainer) {
        widgetList = parentContainer.widgetList || []
      } else {
        return
      }
    }

    const filteredList = widgetList.filter(item => item != null)
    const index = filteredList.findIndex(item => item.id === selectedWidget.id)
    
    if (index === -1 || index + 1 >= filteredList.length) return

    // 交换位置
    const temp = filteredList[index + 1]
    filteredList[index + 1] = filteredList[index]
    filteredList[index] = temp

    // 更新原 widgetList
    if (parentContainer) {
      parentContainer.widgetList = [...filteredList]
    } else {
      this.designer.widgetList = [...filteredList]
    }
    
    this.$nextTick(() => {
      this.setCurrentKey(selectedWidget.id)
    })
    this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK)
  }
},

// 添加的新方法：查找父容器
findParentContainer(widgetList, widgetId) {
  for (const widget of widgetList) {
    if (!widget) continue
    
    if (widget.widgetList && widget.widgetList.length > 0) {
      // 检查当前widget的子组件中是否包含目标组件
      const found = widget.widgetList.some(child => child && child.id === widgetId)
      if (found) {
        return widget
      }
      
      // 递归检查子组件的子组件
      const parent = this.findParentContainer(widget.widgetList, widgetId)
      if (parent) {
        return parent
      }
    }
  }
  return null
},
    copyPage() {
      if (!this.designer) {
        this.$message.warning('请先选择要复制的页面')
        return
      }
      this.$confirm(`确定要复制 ${this.designer.options.name} 页面吗？`)
        .then(() => {
          this.$emitter.emit(EVENTS.COPY_PAGE, this.designer)
        })
        .catch(() => { })
    },
    deleteAllPage() {
      this.$confirm(`确定要删除除main_ui之外的所有页面吗？`)
        .then(() => {
          this.$emitter.emit(EVENTS.DELETE_ALL_PAGE)
        })
        .catch(() => { })
    }
  }
}
</script>

<style lang="scss" scoped>
.variable-info {
  padding: 5px 12px;
  margin-bottom: 5px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
  font-size: 12px;
  color: #606266;
}
.panel-container {
  width: 100%;

  :deep(.el-space__item) {
    width: 100%;
  }

  :deep(.el-tabs) {
    padding: 0 4px 0 0;
  }

  .page-toolbar {
    :deep(.el-button) {
      margin-left: 2px;
    }

    svg {
      width: 1.2em;
      height: 1.2em;
    }
  }

  .setting-scrollbar {
    .setting-form {
      padding: 0 6px;

      :deep(.el-form-item__label) {
        font-size: 11px;
        overflow: hidden;
        white-space: nowrap;
      }

      :deep(.el-form-item--small.el-form-item) {
        margin-bottom: 10px;
      }

      :deep(.el-slider) {
        .el-slider__runway {
          margin-right: 16px;
        }

        .el-slider__input {
          width: 85px !important;
        }
      }

      :deep(.el-select) {
        width: 178px !important;
      }

      .setting-collapse {
        :deep(.el-collapse-item__content) {
          padding-bottom: 6px;
        }

        :deep(.el-collapse-item__header) {
          font-style: italic;
          font-weight: bold;
          font-size: 12px;
          height: 32px;
          line-height: 32px;
        }
      }
    }
  }

  :deep(.node-tree) {
    font-size: 11px;

    .el-tree-node.is-current>.el-tree-node__content {
      background: #ffeaa6 !important;
    }

    .el-tree-node .el-tree-node__content:hover {
      background: #ffeaa6 !important;
    }
  }
}

/* 隐藏Chrome浏览器中el-input数字输入框右侧的上下调整小箭头 */
:deep(.hide-spin-button) input::-webkit-outer-spin-button,
:deep(.hide-spin-button) input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

/* 隐藏Firefox浏览器中el-input数字输入框右侧的上下调整小箭头 */
:deep(.hide-spin-button) input[type='number'] {
  appearance: textfield;
}

:deep(.custom-divider.el-divider--horizontal) {
  margin: 10px 0;
}

:deep(.custom-divider-margin-top.el-divider--horizontal) {
  margin: 20px 0;
}
</style>
